/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "NodeCpp/Data/Rel/Details/MySQLConnection.h"

namespace NodeCpp {
namespace Data {
namespace Rel {


    bool MySQLConnection::Open(const std::string& _Host,
        const std::string& _Port, const std::string& _User,
        const std::string _Password, const std::string& _Db)
    {
        Res_ = mysql_init(NULL);

        do
        {
            int _Lport;
            const char* _UnixSocket;

            mysql_options(Res_, MYSQL_SET_CHARSET_NAME, "utf8");
            mysql_options(Res_, MYSQL_OPT_RECONNECT, "1");

            if (_Host == ".")
            {
                unsigned int _Opt = MYSQL_PROTOCOL_PIPE;
                mysql_options(Res_, MYSQL_OPT_PROTOCOL, &_Opt);
                _Lport = 0;
                _UnixSocket = NULL;
            }
            else
            {
                _Lport = atoi(_Port.c_str());
                _UnixSocket = NULL;
            }


            /* Auto reconnect */
            char _Value = 1;
            mysql_options(Res_, MYSQL_OPT_RECONNECT, &_Value);

            /* Real connect */
            if (!mysql_real_connect(Res_, _Host.c_str(), _User.c_str(),
                _Password.c_str(), _Db.c_str(), _Lport, _UnixSocket, 0))
            {
                _HandleError();
                mysql_close(Res_);
                Res_ = NULL;
                break;
            }

        } while (false);

        return Res_ != NULL;
    }

}}}